package code.sbxj.qwd.com.sbxj;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.CacheDiskUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.UnsupportedEncodingException;


@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {

    @ViewInject(R.id.listview)
    private ListView listview;


    MyAdapter myadapter;
    JSONArray dataArray = new JSONArray();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NfcUtils nfcUtils = new NfcUtils(this);
        getUserInfo();

        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //开启前台调度系统
        NfcUtils.mNfcAdapter.enableForegroundDispatch(this, NfcUtils.mPendingIntent, NfcUtils.mIntentFilter, NfcUtils.mTechList);

    }
    @Override
    protected void onPause() {
        super.onPause();
        //关闭前台调度系统
        NfcUtils.mNfcAdapter.disableForegroundDispatch(this);
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //当该Activity接收到NFC标签时，运行该方法
        //调用工具方法，读取NFC数据
        try {
            String str = NfcUtils.readNFCFromTag(intent);
            Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    void initView() {
        myadapter = new MyAdapter();
        listview.setAdapter(myadapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=new Intent();
                intent.setClass(MainActivity.this,CheckLineActivity.class);
                try {
                    intent.putExtra("linename",dataArray.getJSONObject(i).optString("lineName"));
                    intent.putExtra("lineid",dataArray.getJSONObject(i).optInt("lineId"));
                    startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    class MyAdapter extends BaseAdapter {
        private LayoutInflater mInflater;


        //返回数据集的长度
        @Override
        public int getCount() {
            return dataArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return dataArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        //这个方法才是重点，我们要为它编写一个ViewHolder
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            convertView = getLayoutInflater().inflate(R.layout.activity_taskiterm, null);

            TextView linename=convertView.findViewById(R.id.linename);
            TextView deptname=convertView.findViewById(R.id.deptname);
            me.zhouzhuo.zzhorizontalprogressbar.ZzHorizontalProgressBar progressbar=convertView.findViewById(R.id.pb);
            try {
                linename.setText(position+ " "+dataArray.getJSONObject(position).optString("lineName"));
                deptname.setText(dataArray.getJSONObject(position).optString("deptName"));
                int totlecount=dataArray.getJSONObject(position).optInt("total");
                int finishcount=dataArray.getJSONObject(position).optInt("finishCount");
                if(totlecount>0){
                    progressbar.setProgress(finishcount*100/totlecount);
                }else{
                    progressbar.setProgress(0);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return convertView;
        }


    }

    private void getUserInfo() {
        ShowLoading();
        RequestParams params = new RequestParams(Config.BaseUrl + "mgr/currentInfo");
        params.setUseCookie(true);
        params.addHeader("cookie", CacheDiskUtils.getInstance().getString("cookie"));
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                Log.e("result", result);

                try {
                    JSONObject obj = new JSONObject(result);
                    setTitleText("欢迎：" + obj.optString("deptName") + "--" + obj.optString("name"));
                    getTasklist(obj.optInt("deptId"));
                    CacheDiskUtils.getInstance().put("userid",obj.optInt("deptId")+"");

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void getTasklist(int deptId) {
//        ShowLoading();
        RequestParams params = new RequestParams(Config.BaseUrl + "task/processingList?deptId="+deptId);
        params.setUseCookie(true);
        params.addHeader("cookie", CacheDiskUtils.getInstance().getString("cookie"));
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                Log.e("result", result);

                try {
                    dataArray = new JSONArray(result);
                    myadapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                CancleLoading();
            }
        });
    }
}
